package com.heitian.ssm.controller.api;

import cc.openkit.common.KitUtil;
import com.alibaba.fastjson.JSONObject;
import com.heitian.ssm.controller.common.ApiCommon;
import com.heitian.ssm.model.CallRecord;
import com.heitian.ssm.service.CallRecordService;
import com.heitian.ssm.util.StaticFinalVar;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/api")
public class ApiController {

    private Logger log = Logger.getLogger(ApiController.class);

    private static String appkey = "05f919fc569c45e7a2d1a3a6f342d2df";

    private static String salt = "59e3b3f7a68a45a483c14175efab413b";

    private static String appId = "softPhone";

    @Resource
    private CallRecordService callRecordService;

    /**
     * 图片上传接口 -- 用于layui
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getCallId", method = RequestMethod.POST)
    @ResponseBody
    public Object getCallId(HttpServletRequest request) throws Exception {
        log.info("录音调取接口");
        String reqKey = request.getParameter("reqKey");
        String reqDate = request.getParameter("reqDate");
        String place = request.getParameter("place");

        if(!KitUtil.feikong(reqKey)||!KitUtil.feikong(reqDate)||!KitUtil.feikong(place)){
            return JSONObject.toJSON(KitUtil.returnMap("4001", StaticFinalVar.PARAMETER_ERR));
        }
        String key = KitUtil.md5(KitUtil.md5(appId +"openkit"+appkey+"openkit"+ reqDate)+salt);
        if(!reqKey.equals(key)){
            return JSONObject.toJSON(KitUtil.returnMap("4001", StaticFinalVar.APP_ERR));
        }

        CallRecord callRecord = callRecordService.getCallRecord(place);

        Map<String, Object> map = new HashMap<String, Object>();
        // 保存前台传来的缩略图
        if(callRecord!=null){
            map.put("code", 0);
            map.put("callId", callRecord.getCallId());
        }else{
            map.put("code", 0);
            map.put("callId", "");
        }
        return map;
    }

    /**
     * 图片上传接口 -- 用于layui
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/inComingCall", method = RequestMethod.POST)
    @ResponseBody
    public Object inComingCall(HttpServletRequest request) throws Exception {
        log.info("弹窗接口");
        String type = request.getParameter("type");
        String number = request.getParameter("number");
        String connId = request.getParameter("connId");
        String place = request.getParameter("place");
        String sessionId = request.getParameter("sessionId");

        if(!KitUtil.feikong(type)||!KitUtil.feikong(number)||!KitUtil.feikong(connId)||!KitUtil.feikong(place)||!KitUtil.feikong(sessionId)){
            return JSONObject.toJSON(KitUtil.returnMap("4001", StaticFinalVar.PARAMETER_ERR));
        }
        String result = null;
		result = interfaceUtil("http://10.128.0.13/api/thirdCallServlet/incomingcall?type="+type+"&callerNumber="+number
				+"&receiverNumber="+place+"&callid="+connId+"&sessionid="+sessionId, "");
		if(!KitUtil.feikong(result)){
			result = interfaceUtil("http://10.128.0.12/api/thirdCallServlet/incomingcall?type="+type+"&callerNumber="+number
					+"&receiverNumber="+place+"&callid="+connId+"&sessionid="+sessionId, "");
		}
        Map<String, Object> map = new HashMap<String, Object>();
        // 保存前台传来的缩略图
        map.put("code", 0);
        map.put("result",result);
        return map;
    }

    public static void main(String[] args) {
        String result = interfaceUtil("http://restapi.amap.com/v4/geofence/status?key=9e43bb2f2520ad9ef8d873cb27bb7aed&diu=864698039636093&locations=118.72553,31.995475,1530588986;118.72789,31.994784,1530589086&uid=001", "");
        System.out.println(result);
    }
    public static String interfaceUtil(String path,String data) {
        String result = "";
        try {
            URL url = new URL(path);
            //打开和url之间的连接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            PrintWriter out = null;
            //请求方式
//          conn.setRequestMethod("POST");
//           //设置通用的请求属性
            //conn.setRequestProperty("Authorization", "Basic b3BzOm9wcw==");
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
            //设置是否向httpUrlConnection输出，设置是否从httpUrlConnection读入，此外发送post请求必须设置这两个
            //最常用的Http请求无非是get和post，get请求可以获取静态页面，也可以把参数放在URL字串后面，传递给servlet，
            //post与get的 不同之处在于post的参数不是放在URL字串里面，而是放在http请求的正文内。
            conn.setDoOutput(true);
            conn.setDoInput(true);
            //获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            //发送请求参数即数据
            out.print(data);
            //缓冲数据
            out.flush();
            //获取URLConnection对象对应的输入流
            InputStream is = conn.getInputStream();
            //构造一个字符流缓存
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String str = "";
            while ((str = br.readLine()) != null) {
                result = result + str;
            }
            //关闭流
            is.close();
            //断开连接，最好写上，disconnect是在底层tcp socket链接空闲时才切断。如果正在被其他线程使用就不切断。
            //固定多线程的话，如果不disconnect，链接会增多，直到收发不出信息。写上disconnect后正常一些。
            conn.disconnect();
            System.out.println("完整结束");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}
